<?php
/**
 * 作用：文章资讯模块
 * 作者: shijy@soe-soe.com
 * 日期: 2016/5/12 11:33
 * 公司: 浙江宣逸网络科技有限公司<www.soe-soe.com>
 */


namespace Common\Model;
class ArticleModel extends BaseModel{
	static $instance=null;
	public function getInstance(){
		if(!self::$instance){
			self::$instance=M('article',null,DB_MAIN_CFG);
		}
		return self::$instance;
	}

	public static  function  getAuditStatus(){
		return array(
			AUDIT_DEFAULT => "未审核",
			AUDIT_PASS => "审核通过",
			AUDIT_UNPASS => "审核不通过",
		);
	}

	public static function getEliteStatus(){
		return array(
			ELITE_NO => "非精华",
			ELITE_YES => "精华",
		);
	}

	//投稿图处文字分隔字符
	const CONTRIBUTE_SEPARATOR='#|!|#';

	/**
	 * 获取文章详情
	 * Author: shijy
	 * @param int $articleId
	 * @return array
	 */
	public static function getArticleDetail($articleId=0,$uid){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$articleId){
			return $dataFailure;
		}

		$where="id={$articleId}";
		$articleM=self::getInstance();
		$articleInfo=$articleM->where($where)->find();
		if(!$articleInfo){
			$dataFailure['msg']='指定文件不存在';
			return $dataFailure;
		}
		$articleM->where($where)->setInc('viewNum');
		

		$author=$articleInfo['uid']+0;
		$userTag=M('u_user_base',null,DB_MAIN_CFG)->where('uid='.$author)->getField('userTag');
		$cfg_utag=getUTagKv();

		$articleInfo['userTag']=$userTag;
		$articleInfo['userTagHtml'] = $cfg_utag[$userTag];
		$dataSuccess['data']=$articleInfo;

		return $dataSuccess;
	}




	/**
	 * 获取文章列表数据
	 * Author: shijy
	 * @param $channel 文章频道
	 * @param $uid 对应用户
	 * @param $page 当前码
	 * @param int $pageSize 页大小
	 * @return array
	 */
	public static function getArticleList($channel=0,$uid=0,$page=1,$pageSize=10,$clientShow=CLIENT_SHOW_ALL,$keyword=null){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$M=self::getInstance();
		$where='1';
		if($channel>0){
			$where .=" and find_in_set({$channel},channel)";
		}
		if($uid>0){
			$where .=" and (uid={$uid} or audit=".AUDIT_PASS.") ";
		}else{
			$where .=" and audit=".AUDIT_PASS;
		}
		if($keyword){
			$where .=" and title like '%{$keyword}%'";
		}



		//展现客户端类型
		if($clientShow!=CLIENT_SHOW_ALL){
			$where .=" and find_in_set({$clientShow}, clientShow)";
		}


		$rowCount=$M->where($where)->count();

		$pageCount=max(1,ceil($rowCount/$pageSize));
		$page=max($page,1);
		$offset=($page-1)*$pageSize;
		$list=$M->where($where)
			//->field('content',true)
			->order('id desc')
			->limit($offset,$pageSize)
			->select();
		
		
		$dataSuccess['total']=$rowCount;
		$dataSuccess['totalPage']=$pageCount;
		$dataSuccess['page']=$page;
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页

		//是否关注及获取用户标签
		$tagKv = getUTagKv();
		foreach($list as $key => $val){
			if(!$val['nickname']){
				$list[$key]['nickname']=SELF_NAME;
			}
			
			$list[$key]['follow']=0;
			if($uid){
				$list[$key]['follow'] = M('friendship', null, DB_MAIN_CFG)->where("uid={$uid} and status=1 and fid=".$val['uid'])->getField('status') ? 1 : 0;
				if ($list[$key]['follow']) {
					$list[$key]['follow'] = M('friendship', null, DB_MAIN_CFG)->where("fid={$uid} and status=1 and uid=".$val['uid'])->getField('status') ? 2 : 1;
				}
			}
			$tag = M('u_user_base', null, DB_MAIN_CFG)->where("uid=".$val['uid'])->getField('userTag');
			$list[$key]['userTag']=$tag;
			$list[$key]['userTagHtml']=$tagKv[$tag];
			//喜欢
			$list[$key]['done'] = M('praise_log',null,DB_MAIN_CFG)->where("objID='$val[id]' and uid={$uid} and objType=".OBJ_TYPE_ARTICLE)->find()?1:0;
		}

		$dataSuccess['data']=$list;
		return $dataSuccess;
	}

	/**
	 * PC获取每周热门
	 * User: Rick.Sun.<sunwgjj@126.com>
	 * Return: array
	 * Address: 浙江宣逸网络科技有限公司
	 * @return array
	 */
	public static function getEveryHot(){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$data = array();
		$list=M("cfg_config",null,DB_MAIN_CFG)->where(" cfgName = 'EVERY_HOT_FOR_PC' ")->find();
		if($list){
			$list['cfgValue'] = unserialize($list['cfgValue']);
			foreach($list['cfgValue'] as $key=>$val){
				switch($val['type']+0){
					case OBJ_TYPE_ACTIVITY:
						$data[$key]=M("e_events",null,DB_MAIN_CFG)->field('id,title,imgList as img')->where(" id = '{$val['id']}' ")->find();
						$data[$key]['uri']=u("Web/Events/info?id=".$val['id']);
						break;
					case OBJ_TYPE_ARTICLE:
						$data[$key]=M("article",null,DB_MAIN_CFG)->field('id,title,listPic as img')->where(" id = '{$val['id']}' ")->find();
						$data[$key]['uri']=u("Web/Article/detail?id=".$val['id']);
						break;
					case OBJ_TYPE_POINTMALL:
						$data[$key]=M("point_mall",null,DB_MAIN_CFG)->field('id,titleInner as title,listPic as img')->where(" id = '{$val['id']}' ")->find();
						$data[$key]['uri']=u("Web/PointMall/article?id=".$val['id']);
						break;
					case OBJ_TYPE_STORE:
						$data[$key]=M("point_mall",null,DB_MAIN_CFG)->field('id,titleInner as title,listPic as img')->where(" id = '{$val['id']}' ")->find();
						$data[$key]['uri']=u("Web/Business/detail?id=".$val['id']);
						break;
					default:
				}
			}
		}

		$dataSuccess['data']=$data;
		return $dataSuccess;
	}


	//获取我的发稿(也用于获取其他用户的自己的发稿)
	public static function getMyArticleList($uid,$page,$pageSize,$fid=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$uid){
			$dataFailure['msg']='请指定用户';
			return $dataFailure;
		}

		$dataSuccess['total'] = self::getInstance()->where("uid ={$uid}")->count();	//获取数据总条数
		$dataSuccess['page'] = $page ? $page :1;												//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);						//总页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >=$dataSuccess['totalPage']?0:1;		//是否还有下一页
		$offset = ($dataSuccess['page']-1)*$pageSize;

		$list = self::getInstance()
			->where("uid = {$uid}")
			->limit($offset,$pageSize)
			->order("addTime DESC")->select();

//		喜欢
		foreach($list as $k =>$v){
			$list[$k]['done'] = M('praise_log',null,DB_MAIN_CFG)->where("objID='$v[id]' and uid={$uid} and objType=".OBJ_TYPE_ARTICLE)->find()?1:0;
		}

		if($fid){
			//我是否关注了该用户
			$dataSuccess['followed'] = M('friendship',null,DB_MAIN_CFG)->where("uid={$fid} and fid={$uid} and status=1")->find()?1:0;
			//该用户的粉丝数
			$dataSuccess['followNum'] = M('friendship',null,DB_MAIN_CFG)->where("fid={$uid} and status=1")->count();
		}
		$dataSuccess['data'] = $list;
		return $dataSuccess;
	}

	/**
	 * 保存投稿的草稿页
	 * Author: shijy
	 * @param $uid
	 * @param $title
	 * @param $listPic
	 * @param $content
	 * @return array
	 */
	public static function saveDraft($uid,$title,$listPic,$content){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');

		$data=array();
		$data['uid']=$uid;
		$data['title']=$title;
		$data['listPic']=$listPic;
		$data['addTime']=time();
		$data['content']=$content;
		$draftM=M('u_draft',null,DB_MAIN_CFG);
		$tmp=$draftM->where("uid={$uid}")->find();
		if(!$tmp){
			$draftM->add($data);
		}else{
			$draftM->save($data);
		}
		return $dataSuccess;
	}


	/**
	 * 返回草稿
	 * Author: shijy
	 * @param $uid
	 * @return mixed
	 */
	public static function getDraft($uid){
		$draftM=M('u_draft',null,DB_MAIN_CFG);
		$tmp=$draftM->where("uid={$uid}")->find();
		if(!$tmp){
			return null;
		}
		$tmp['content']=explode(ArticleModel::CONTRIBUTE_SEPARATOR,$tmp['content']);
		$imgEXT=array('jpg','gif','png');
		foreach($tmp['content'] as $k=>$v){
			if( in_array(strtolower(substr($v,-3)),$imgEXT)){
				$tmp['content'][$k]=array(1,$v);
			}else{
				$tmp['content'][$k]=array(0,$v);
			}
		}
		return $tmp;
	}

	/**
	 * 保存正式投稿,来自WAP
	 * Author: shijy
	 * @param $uid
	 * @param $title
	 * @param $listPic
	 * @param $contentRaw array()
	 */
	public static function saveContributeFromWAP($uid,$title,$listPic,$contentRaw){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$uid){
			$dataFailure['msg']="请登陆后再投稿";
			return $dataFailure;
		}
		$title=strip_tags($title);
		$titleLen=strlen($title);
		if($titleLen < C('TITLE_LENGTH_MIN') || $titleLen > C('TITLE_LENGTH_MAX')){
			$dataFailure['msg']="标题长度请控制在".C('TITLE_LENGTH_MIN').'至'.C('TITLE_LENGTH_MAX');
			return $dataFailure;
		}

		if(strlen($listPic)<2){
			$dataFailure['msg']='请指定图片';
			return $dataFailure;
		}


		$data=array();
		$data['uid']=$uid;
		$data['title']=strip_tags($title);
		$data['listPic']=$listPic;
		$data['addTime']=time();
		$content=$contentRaw;
//		$imgEXT=array('jpg','gif','png');
//		foreach($contentRaw as $k=>$v){
//			if(strlen($v)<=0){
//				continue;
//			}
//			if( in_array(strtolower(substr($v,-3)),$imgEXT)){//图片
//				$content.="<p><img src=\".{$v}\" /></p>";
//			}else{//文字
//				$v=strip_tags($v);
//				$content.="<p>{$v}</p>";
//			}
//		}
		if(true !== $maskStr = checkCleanWord($content) ){
			$dataFailure['msg'] = "评论内容中不能包含:".$maskStr;
			return $dataFailure;
		}

		if(strlen($content)<2){
			$dataFailure['msg']='填写投稿内容';
			return $dataFailure;
		}

		$data['content']=htmlspecialchars_decode($content);
		//删除草稿
		M('u_draft',null,DB_MAIN_CFG)->where("uid={$uid}")->delete();

		$articleM=self::getInstance();
		$data['nickname']=session('nickname');
		$data['contentType']=CONTENT_TYPE_UNSET;
		$data['channel']=1;
		$data['clientFrom']=CLIENT_FROM_WX;//微信
		$data['audit']=AUDIT_DEFAULT;
		$data['private']=PRIVATE_PUBLIC;
		$articleM->add($data);

		//投稿得积分
		$ret=UserModel::addUserValByAction( $uid,OPT_CONTRIBUTE);
		if($ret['status']==0){
			return $ret;
		}
		return $dataSuccess;
	}

	/**
	 * 保存web端个人中心投稿
	 * Author: wwl
	 * @param $uid
	 * @param $nickname
	 * @param $title
	 * @param $frontPic
	 * @param $content array()
	 */
	public static function saveEditArticleFromWeb($uid,$nickname,$title,$content,$frontPic){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$uid){
			$dataFailure['msg']="请登陆后再投稿";
			return $dataFailure;
		}

		$title=strip_tags($title);
		$titleLen=strlen($title);
		if($titleLen < C('TITLE_LENGTH_MIN') || $titleLen > C('TITLE_LENGTH_MAX')){
			$dataFailure['msg']="标题长度请控制在".C('TITLE_LENGTH_MIN').'至'.C('TITLE_LENGTH_MAX');
			return $dataFailure;
		}

		if(strlen($frontPic)<2){
			$dataFailure['msg']='请指定图片';
			return $dataFailure;
		}

		$data = array(
			'uid' 		=> $uid,
			'nickname'	=> $nickname,
			'title'		=> $title,
			'listPic'	=> $frontPic,
			'content'	=> htmlspecialchars_decode($content),
			'addTime'	=> time(),
			'channel'	=> 1,
			'clientFrom'=> CLIENT_FROM_PC,//PC
			'audit'		=> AUDIT_DEFAULT,
			'private'	=> PRIVATE_PUBLIC
		);

		$articleM=self::getInstance();
		$articleM->add($data);
		return $dataSuccess;
	}


}